package com.hawk.eye.framework.web.service;

import com.hawk.eye.framework.constant.CacheConstants;
import com.hawk.eye.common.constant.Constants;
import com.hawk.eye.framework.constant.UserConstants;
import com.hawk.eye.framework.core.domain.entity.SysRole;
import com.hawk.eye.framework.core.domain.entity.SysUser;
import com.hawk.eye.framework.core.domain.model.RegisterBody;
import com.hawk.eye.framework.cache.ICache;
import com.hawk.eye.framework.exception.user.CaptchaException;
import com.hawk.eye.framework.exception.user.CaptchaExpireException;
import com.hawk.eye.framework.utils.MessageUtils;
import com.hawk.eye.framework.utils.SecurityUtils;
import com.hawk.eye.framework.utils.StringUtils;
import com.hawk.eye.framework.manager.AsyncManager;
import com.hawk.eye.framework.manager.factory.AsyncFactory;
import com.hawk.eye.server.service.ISysConfigService;
import com.hawk.eye.server.service.ISysRoleService;
import com.hawk.eye.server.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 注册校验方法
 *
 * @author salad
 */
@Component
public class SysRegisterService {

    @Autowired
    private ISysUserService userService;


    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ICache cache;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {
        String username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }
        String msg = validateRegisterBody(registerBody);
        if (StringUtils.isNotEmpty(msg)) {
            return msg;
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            msg = "注册用户'" + username + "'失败，注册账号的已存在";
            return msg;
        }
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setPhonenumber(registerBody.getPhonenumber());


        boolean res = userService.registerUser(sysUser);
        if (!res) {
            msg = "注册失败,请联系系统管理人员";
        } else {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
        }
        return msg;
    }

    public String validateRegisterBody(RegisterBody registerBody) {
        String msg = null;
        if (StringUtils.isEmpty(registerBody.getPhonenumber())) {
            msg = "手机号不能为空";
        } else if (StringUtils.isEmpty(registerBody.getUsername())) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(registerBody.getPassword())) {
            msg = "用户密码不能为空";
        } else if (registerBody.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH
                || registerBody.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (registerBody.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || registerBody.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = cache.get(verifyKey);
        cache.remove(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
